package io.kiki.stack.netty.serialization;

import io.kiki.stack.netty.command.CommandCode;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Setter
@Getter
public class CustomSerializerManager {

    private static final ConcurrentHashMap<String/* class name */, CustomSerializer> classNameToCustomSerializerMap = new ConcurrentHashMap<String, CustomSerializer>();


    private static final ConcurrentHashMap<CommandCode/* command code */, CustomSerializer> commandCodeToCustomSerializerMap = new ConcurrentHashMap<CommandCode, CustomSerializer>();


    public static void registerCustomSerializer(String className, CustomSerializer serializer) {
        CustomSerializer prevSerializer = classNameToCustomSerializerMap.putIfAbsent(className, serializer);
        if (prevSerializer != null) {
            throw new RuntimeException("CustomSerializer has been registered for class: " + className + ", the custom serializer is: " + prevSerializer.getClass().getName());
        }
    }

    public static CustomSerializer getCustomSerializer(String className) {
        if (!classNameToCustomSerializerMap.isEmpty()) {
            return classNameToCustomSerializerMap.get(className);
        }
        return null;
    }


    public static void registerCustomSerializer(CommandCode commandCode, CustomSerializer serializer) {
        CustomSerializer prevSerializer = commandCodeToCustomSerializerMap.putIfAbsent(commandCode, serializer);
        if (prevSerializer != null) {
            throw new RuntimeException("CustomSerializer has been registered for command code: " + commandCode + ", the custom serializer is: " + prevSerializer.getClass().getName());
        }
    }


    public static CustomSerializer getCustomSerializer(CommandCode code) {
        if (!commandCodeToCustomSerializerMap.isEmpty()) {
            return commandCodeToCustomSerializerMap.get(code);
        }
        return null;
    }

    public static void clear() {
        classNameToCustomSerializerMap.clear();
        commandCodeToCustomSerializerMap.clear();
    }
}
